const axios = require('../utils/axios');
const dayjs = require('dayjs');
const sqlConn2136 = require('../utils/sqlserver2136')
const sqlConn2132 = require('../utils/sqlserver2132')

const tianapiHolidayURL = 'https://apis.tianapi.com/jiejiari/index'
const yunpianURL = 'https://sms.yunpian.com/v2/sms/batch_send.json'

exports.getKqRecord = async (req, res) => {
   try {
      const { checkType } = req.body;//1为早7:50晚18:30提醒，2为早7:55晚17:50提醒，3为不检测
      // console.log("checkType", checkType);    

      //调用第三方商业接口，天聚数行，获取指定日期的节假日信息
      const requestData = {
         key: '77969958dfb8855dca9adfae031daa92',
         date: dayjs().add(0, 'day').format('YYYY-MM-DD'), // 使用请求中的日期或默认值
         type: 0
      };
      const resHoliday = await axios.post(tianapiHolidayURL, requestData, {
         headers: {//此api在请求时要求enctype应为application/x-www-form-urlencoded
            'Content-Type': 'application/x-www-form-urlencoded'
         }
      });
      // console.log("调用接口", resHoliday.result.list[0])
      //工作日调休日时才发送短信，daycode为0表示工作日、为1节假日、为2双休日、3为调休日(上班)
      if (resHoliday.result.list[0].daycode == 0 || resHoliday.result.list[0].daycode == 3) {

         let userid = ''
         let mobileList = ''

         //从2136数据库中读取所有需要检测的用户   
         const sqlstr = `select * from ZKTIME where USERTYPE=${checkType}`
         const result = await sqlConn2136(sqlstr)
         for (let i = 0; i < result.rowsAffected[0]; i++) {
            if (result.recordset[i].USERTYPE == 3)//3是特殊占用
               continue;
            userid = userid + "'" + result.recordset[i].USERID + "',";
         }
         userid = userid.substring(0, userid.length - 1);
         // console.log("数据库查询结果3", userid);
         if (userid.length == 0) {
            res.status(200).json({
               code: 200,
               msg: `没有符合条件的用户`,
            });
            //写日志
            const sqlstrlog = `insert into ZKTIME_LOG (LOGTYPE,LOGCONTENT,LOGTIME) values ('系统自动','完成检测，没有符合条件的用户！',getdate())`
            await sqlConn2136(sqlstrlog)        
            return;
         }

         //从2136数据库拿到工号后，再从2132数据库查询预先设定好的哪些用户未打卡
         const moningstarttime = '04:00:00'
         const moningendtime = '07:59:59'
         const nightstarttime = '17:30:00'
         const nightendtime = '22:00:00'
         let sqlstr1 = `SELECT u.badgenumber
                           FROM userinfo u
                           LEFT JOIN checkinout c ON u.userid = c.userid
                           AND c.checktime BETWEEN CAST(CAST(getdate() AS date) AS datetime) + '${moningstarttime}' AND 
                           CAST(CAST(getdate() AS date) AS datetime) + '${moningendtime}'
                           WHERE u.badgenumber IN (${userid})
                           AND c.userid IS NULL`
         if (dayjs().isAfter(dayjs().add(0, 'day').format('YYYY-MM-DD 17:30:00'))) {
            sqlstr1 = `SELECT u.badgenumber
                           FROM userinfo u
                           LEFT JOIN checkinout c ON u.userid = c.userid
                           AND c.checktime BETWEEN CAST(CAST(getdate() AS date) AS datetime) + '${nightstarttime}' AND 
                           CAST(CAST(getdate() AS date) AS datetime) + '${nightendtime}'
                           WHERE u.badgenumber IN (${userid})
                           AND c.userid IS NULL`
         }
         const result1 = await sqlConn2132(sqlstr1)
         userid = '';
         for (let i = 0; i < result1.rowsAffected[0]; i++) {
            userid = userid + "'" + result1.recordset[i].badgenumber + "',";
         }
         // console.log("执行1", userid.length, sqlstr1);
         if (userid.length > 0) {
            userid = userid.substring(0, userid.length - 1);
            console.log("没打卡用户的工号：", userid);

            //获取没有打卡那些用户的手机号
            const sqlstr2 = `select MOBILE from ZKTIME where USERID in (${userid})`
            const result2 = await sqlConn2136(sqlstr2)
            for (let i = 0; i < result2.rowsAffected[0]; i++) {
               mobileList = mobileList + result2.recordset[i].MOBILE + ",";
            }
            mobileList = mobileList.substring(0, mobileList.length - 1);
            console.log("没打卡用户的手机号：", mobileList);

            //发送短信通知
            const requestDataYP = {
               apikey: '0c21b24d20ca1f3459dbcd067d657112',
               text: '【四川省达州钢铁集团】温馨提示，系统中未发现您的考勤记录，请及时打卡。',
               mobile: mobileList,
            }
            const responseYP = await axios.post(yunpianURL, requestDataYP, {
               headers: {
                  'Content-Type': 'application/x-www-form-urlencoded'
               }
            });
            res.status(200).json({
               code: 200,
               msg: `发送短信通知成功`,
               data: responseYP.data
            });

            //写日志
            const sqlstrlog = `insert into ZKTIME_LOG (LOGTYPE,LOGCONTENT,LOGTIME) values ('系统自动','${mobileList}忘记打卡',getdate())`
            console.log('sql执行2', sqlstrlog);
            await sqlConn2136(sqlstrlog)
            // console.log("写日志结果1：", responseYP);
         } else {

            res.status(200).json({
               code: 200,
               msg: `所有预设用户考勤记录正常!`,
            });
            //写日志
            const sqlstrlog = `insert into ZKTIME_LOG (LOGTYPE,LOGCONTENT,LOGTIME) values ('系统自动','完成检测，所有设定用户考勤均正常！UserType=${checkType}',getdate())`
            await sqlConn2136(sqlstrlog)
            // console.log('sql执行', sqlstrlog);
         }
         return;
         // const response = await axios.post(kqRecodeURL, req.body);
      }

      res.json({
         code: 200,
         message: `完成检测`,
      });
      //写日志
      const sqlstrlog = `insert into ZKTIME_LOG (LOGTYPE,LOGCONTENT,LOGTIME) values ('系统自动写入','完成检测，第三方商业接口天聚数行反馈今日为：${resHoliday.result.list[0].info}',getdate())`
      await sqlConn2136(sqlstrlog)
      console.log("写日志结果6：", resHoliday.result.list[0].info);
      // 调用第三方API
      //  const response = await axios.get(kqRecodeUrl, {
      //    param1: 'value1'
      //  });
   } catch (error) {
      res.status(500).json({
         code: 500,
         message: '调用第三方API失败',
         error: error.message
      });
   }
};